<!--
 * @Author: 江沅锋 yuanfeng.jiang@symbio.com.cn
 * @Date: 2024-12-19 15:31:27
 * @LastEditors: 江沅锋 yuanfeng.jiang@symbio.com.cn
 * @LastEditTime: 2024-12-24 11:21:19
 * @FilePath: \snow-frontend-pc\src\views\projects\procurement\centralizedPurchasing\components\associatedItem.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <el-dialog
    v-model="visible"
    :title="uploadFileType === 'change' ? '上传附件' : '查看附件'"
    destroy-on-close
    width="700px"
    @close="handleCancel"
  >
    <div class="dialog">
      <div class="changeProgress" v-if="uploadFileType === 'change'">
        <el-form
          :inline="true"
          :model="formInline"
          :rules="rules"
          :label-position="'right'"
          ref="formRef"
          class="demo-form-inline"
          :label-width="'130px'"
        >
          <el-row :gutter="20">
            <el-col :span="20">
              <el-form-item label="选择附件" prop="documentAttachmentArr">
                <ecm-upload
                  :files="defaultFileList"
                  :maxLen="1"
                  @set-file="
                    fileList => {
                      handleChange(fileList);
                    }
                  "
                ></ecm-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="detailProgress" v-else>
        <el-skeleton :rows="8" :loading="loading" animated :height="'200px'">
        </el-skeleton>
        <el-table
          :data="state.fileData"
          height="500px"
          stripe
          v-show="!loading"
          style="width: 100%; margin-top: 20px"
          row-key="id"
          ref="tableDataRef"
          :header-cell-style="{
            background: '#F7F9FD',
            color: '#000',
            height: '48px',
            borderTop: '1px soild #E4E8F2'
          }"
        >
          <template #empty>
            <el-empty :image-size="150" description="暂无数据"></el-empty>
          </template>
          <el-table-column label="附件名称" width="500">
            <template #default="{ row }">
              <el-button
                type="text"
                class="shot-text"
                @click="fileClick(row.documentAttachmentArr[0])"
              >
                {{ row.documentName }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160">
            <template #default="{ row }">
              <el-popconfirm
                :title="`是否删除附件：${row.documentName}？`"
                @confirm="deleteClick(row)"
              >
                <template #reference>
                  <el-button type="text" color="#F56C6C"> 删除 </el-button>
                </template>
              </el-popconfirm>
              <el-button type="text" @click="documenDownLoadClick(row)">
                下载
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel"> 取消 </el-button>
        <el-button
          type="primary"
          :loading="btnLoading"
          @click="handleSure"
          v-if="uploadFileType === 'change'"
        >
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, defineProps, defineEmits, watch } from "vue";
import {
  thdDocumentAdd,
  thdDocumentList,
  thdDocumentDelete
} from "/@/api/projects";
import ecmUpload from "/@/components/ecmUpload/index.vue";
import NotifMessage from "/@/utils/message/notification";
import { downloadFile } from "/@/utils/ecm";
const formRef = ref<HTMLFormElement | null>(null) as any;
const tableDataRef = ref<HTMLElement | null>(null) as any;
const emit = defineEmits(["submit"]);
const visible = ref(false);
const btnLoading = ref<boolean>(false);
const defaultFileList = ref<any>([]);
const loading = ref<boolean>(false);
let state = reactive({
  fileData: []
}) as any;

let formInline = reactive({
  documentAttachmentArr: []
});
const rules = {
  documentAttachmentArr: [
    { required: true, message: "请上传附件", trigger: "change" }
  ]
};
const props = defineProps({
  showDialog: {
    type: Boolean,
    default: false
  },
  pitchDetail: {
    type: Object,
    default: () => {}
  },
  uploadFileType: {
    type: String,
    default: ""
  }
});
watch(
  () => props.showDialog,
  newVal => {
    visible.value = newVal;
    if (newVal) {
      initData();
    }
  }
);
const initData = () => {
  if (props.uploadFileType === "change") {
    defaultFileList.value = [];
    formInline.documentAttachmentArr = [];
  } else {
    getDocumentList();
  }
};
const getDocumentList = () => {
  loading.value = true;
  thdDocumentList({
    bizId: props.pitchDetail.id,
    moduleType: 8,
    pageIndex: 1,
    pageSize: 9999
  })
    .then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        state.fileData = data.list;
        console.log(data.list);
      }
    })
    .finally(() => {
      loading.value = false;
    });
};
const handleChange = (fileList: any) => {
  defaultFileList.value = fileList;
  formInline.documentAttachmentArr = fileList;
};
const handleCancel = () => {
  emit("submit", "cancel");
};
const handleSure = async () => {
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  if (!isValid) return;
  const { documentAttachmentArr } = formInline;
  const params = {
    documentName: documentAttachmentArr[0].name,
    bizId: props.pitchDetail.id, //集采标段ID
    remarks: "",
    documentAttachmentArr,
    moduleType: 8 //集采标段上传的文档
  };
  btnLoading.value = true;
  thdDocumentAdd(params)
    .then((res: any) => {
      if (res.code === 200) {
        NotifMessage.success(`操作成功`);
        emit("submit", "sure");
      }
    })
    .finally(() => {
      btnLoading.value = false;
    });
};
const deleteClick = (row: any) => {
  thdDocumentDelete({
    id: row.id
  }).then((res: any) => {
    if (res.code === 200) {
      NotifMessage.success(`操作成功`);
      getDocumentList();
      emit("submit", "update");
    }
  });
};
const fileClick = (row: any) => {
  window.open(
    `${location.origin}${location.pathname}#/preview?uuidFile=${row.uuidFile}&fileName=${row.fileName}`
  );
};
const documenDownLoadClick = (row: any) => {
  const { documentAttachmentArr } = row;
  downloadFile(
    documentAttachmentArr[0].uuidFile,
    documentAttachmentArr[0].fileName
  );
};
</script>
<style scoped lang="scss">
.dialog {
  width: 100%;
  display: flex;
  border-top: 1px solid #e4e7ed;
  .changeProgress {
    padding: 16px;
  }
  .detailProgress {
    min-height: 200px;
    box-sizing: border-box;
    padding: 20px;
  }
}
.width-custom {
  width: 250px !important;
}
</style>
